package ihuoui.mq.store.test;

import java.io.File;
import java.util.Date;
import java.util.concurrent.atomic.AtomicLong;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import ihuoui.mq.store.CommitLog;
import ihuoui.mq.store.Mess;
import ihuoui.mq.store.StoreException;

public class CommitLogThreads2Files {
	final static CommitLog commitLog = new CommitLog();
	final static Integer total = 100*10000;
	final static Date start=new Date();
	static AtomicLong writeNo=new AtomicLong(0l);
	static AtomicLong readNo=new AtomicLong(0l);
	

	@After
	@Before
	public void clealFile() {
		DeleteDirectory.deleteDir(new File("target/unit_test_store/MappedFileTest/"));
	}

	@SuppressWarnings("static-access")
	@Test
	public void testAppendMessageMulti() {
		System.out.println("start time:"+new Date());
		for (int i = 0; i < 5; i++) {
			WrtiteRun wrtiteRun=new WrtiteRun("T"+i);
			Thread thread=new Thread(wrtiteRun);
			thread.start();
			System.out.println("start :"+"T"+i);
		}
		try {
			Thread.currentThread().sleep(2*60*1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("write:"+writeNo.get());
		System.out.println("read:"+readNo.get());
	}
class WrtiteRun implements Runnable {

	public String topic;
	
	public WrtiteRun(String topic) {
		this.topic=topic;
	}
	
	@Override
	public void run() {
		Mess mess = new Mess();
		mess.setTopic(topic);
		mess.setBody("Once, there was a chance for me!".getBytes());
		try {
			for (int i = 0; i < total; i++) {
				commitLog.appendMessage("target/unit_test_store/MappedFileTest/", mess);
//				System.out.println("T1 write i:" + i);
				writeNo.incrementAndGet();
			}
		} catch (StoreException e1) {
			e1.printStackTrace();
		}

		try {
			Mess read = commitLog.offerMessage("target/unit_test_store/MappedFileTest/", new Long(0),
					mess.getTopic());
			Assert.assertTrue(mess.getTopic().equals(read.getTopic()));
			for (int i = 1; i < total - 1; i++) {
//				System.out.println("T1 read i:" + i);
				read = commitLog.offerNextMessage("target/unit_test_store/MappedFileTest/", mess.getTopic());
				Assert.assertTrue(mess.getTopic().equals(read.getTopic()));
				if (read!=null) {
					readNo.incrementAndGet();
				}
			}
		} catch (StoreException e) {
			e.printStackTrace();
		}
		System.out.println("end time:"+new Date());
		System.out.println("use sec:"+(new Date().getTime()-start.getTime())/1000);
	}
};
	

}
